package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
//import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class DestinationServiceImpl implements IDestinationService {

    @Autowired
    private DestinationRepository repository;


    @Autowired
    private IRegionService regionService;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Destination destination) {
        destination.setId(null);
        repository.save(destination);
    }

    @Override
    public void update(Destination destination) {
        repository.save(destination);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Destination get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> list() {
        return repository.findAll();
    }


    @Override
    public List<Destination> queryDestByRegionId(String rid) {

        //通过区域id查询区域对象,
        Region region = regionService.get(rid);


        //获取对象挂载的目的id集合
        List<String> ids = region.getRefIds();

        //通过id集合查询目的地集合
        //sql: select * from dest where id in (1,2,3...)

        return repository.findByIdIn(ids);
    }

    @Override
    public void saveOrUpdate(Destination destination) {
        if(StringUtils.hasLength(destination.getId())){
            this.update(destination);
        }else{
            this.save(destination);
        }
    }

    @Override
    public Page<Destination> query(DestinationQuery qo) {
        Query query = new Query();

        if(StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }

        //条件
        /*long count = template.count(query, Destination.class);

        if(count == 0){
            return Page.empty();
        }*/

        //当前页数据
       /* Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");*/
        //query.with(pageable);
        //List<Destination> list = template.find(query,Destination.class);




        if(StringUtils.hasLength(qo.getParentId())){
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else{
            //为null
            query.addCriteria(Criteria.where("parentId").is(null));
        }





        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
           Sort.Direction.ASC, "_id");

        //return new PageImpl<>(list,pageable,count);
        return DBHelper.query(template,pageable,query,Destination.class,qo);
    }


    //案例:parentId() : 广州id
    // 中国   广东   广州
    @Override
    public List<Destination> queryToasts(String parentId) {
        List<Destination> list = new ArrayList<>();
        //吐司查询
        /*Destination dest = this.get(parentId);
        list.add(dest);
        if(StringUtils.hasLength(dest.getParentId())){
            Destination d = this.get(dest.getParentId());
            list.add(d);
            if(StringUtils.hasLength(d.getParentId())){
                Destination dd = this.get(d.getParentId());
                list.add(dd);
            }
        }*/

        //循环
        //while(!父对象为null)
        /*while (parentId !=null && !"".equals(parentId)){
              Destination destination = this.get(parentId);
              list.add(destination);
              if(destination.getParentId() != null){
                  parentId = destination.getParentId();
              }else {
                  parentId = null;
              }

        }*/


        //递归
        this.createToast(list, parentId);

        Collections.reverse(list);  //集合翻转

        return list;
    }


    //用于创建toast对象
    // 中国   广东   广州
    //抽取方法做递归
    private void createToast(List<Destination> list, String parentId) {
        //parentID为null时候, 不执行
        if(!StringUtils.hasLength(parentId)){
            return;
        }
        Destination dest = this.get(parentId);
        list.add(dest);
        if(StringUtils.hasLength(dest.getParentId())){
            createToast(list, dest.getParentId());
        }
    }

    @Override
    public List<Destination> queryDestByRegionIdForApi(String regionId) {
        List<Destination> list = new ArrayList<>();

        //第一层
        //区域:国内
        if("-1".equals(regionId)){
            //查询:中国下面所有省份
            list = repository.findByParentName("中国");
        }else{

            //区域:非国内
            list = this.queryDestByRegionId(regionId);
        }

        //第二层
        for (Destination dest : list) {

            //List<Destination> children = repository.findByParentId(dest.getId());

            //约定: 查询子目的地子需要查询前5个
            /*if(children.size() > 5){
                children = children.subList(0, 5);
            }*/

            //jpa 查询方法可以添加分页, 排序操作
            Pageable pageable =
                    PageRequest.of(0, 5, Sort.Direction.ASC, "_id");

            List<Destination> children = repository.findByParentId(dest.getId(), pageable);
            dest.setChildren(children);
        }
        return list;
    }

    @Override
    public Destination queryName(String name) {
        return repository.findByName(name);
    }


}
